package com.lean.android.adsdk

import android.content.Context
import android.text.method.LinkMovementMethod
import android.text.style.AbsoluteSizeSpan
import android.text.style.ForegroundColorSpan
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.Toast
import androidx.appcompat.app.AppCompatDialog
import androidx.core.text.buildSpannedString
import com.lean.android.ad.repository.localcache.AdInfoCache
import com.lean.android.adsdk.databinding.DialogPrivacyBinding
import com.lean.android.adsdk.databinding.LayoutPrivacyActionDefaultBinding
import com.lean.android.adsdk.databinding.LayoutPrivacyActionStrictBinding
import com.lean.android.adsdk.databinding.LayoutPrivacyConfirmBinding
import com.qmuiteam.qmui.kotlin.dip
import com.qmuiteam.qmui.span.QMUIBlockSpaceSpan


class PrivacyDialog(
    private val context: Context,
    strictMode: Boolean = false,
    onAgree: () -> Unit = {},
    onDisagree: () -> Unit = {},
) {

    private val privacyDialog: AppCompatDialog
    private val confirmDialog: AppCompatDialog

    init {
        val binding = DialogPrivacyBinding.inflate(LayoutInflater.from(context))
        privacyDialog = AppCompatDialog(context, R.style.PrivacyDialog_Default).apply {
            setContentView(
                binding.root, ViewGroup.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT
                )
            )
            setCancelable(false)
            setCanceledOnTouchOutside(false)
        }

        binding.content.movementMethod = LinkMovementMethod.getInstance()
        binding.content.text = buildPrivacyContent()


        val confirmBinding = LayoutPrivacyConfirmBinding.inflate(LayoutInflater.from(context))
        confirmBinding.content.text =
            "您需要同意本隐私政策才能继续使用${context.getString(R.string.app_name)}"
        confirmDialog = AppCompatDialog(context, R.style.PrivacyDialog_Default).apply {
            setContentView(
                confirmBinding.root, ViewGroup.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT
                )
            )
            setCancelable(false)
            setCanceledOnTouchOutside(false)
        }


        if (strictMode) {
            val strictBinding =
                LayoutPrivacyActionStrictBinding.inflate(LayoutInflater.from(context))
            binding.privacyActionContainer.addView(strictBinding.root)
            strictBinding.btnAgree.onThrottleClick {
                if (!strictBinding.checkbox.isChecked) {

                    Toast.makeText(context, "请先阅读并同意协议", Toast.LENGTH_SHORT).show()
                } else {
                    onAgree()
                    privacyDialog.dismiss()
                }
            }

            strictBinding.privacyLink.movementMethod = LinkMovementMethod.getInstance()
            strictBinding.privacyLink.text = buildTipsContent(true)

            binding.btnDisagree.onThrottleClick {
                privacyDialog.dismiss()
                onDisagree()
            }

        } else {
            val defaultBinding =
                LayoutPrivacyActionDefaultBinding.inflate(LayoutInflater.from(context))
            binding.privacyActionContainer.addView(defaultBinding.root)

            defaultBinding.privacyLink.movementMethod = LinkMovementMethod.getInstance()
            defaultBinding.privacyLink.text = buildTipsContent()

            defaultBinding.btnAgree.onThrottleClick {//同意
                defaultBinding.agreeText.isSelected = true
                defaultBinding.btnAgree.postDelayed({
                    onAgree()
                    privacyDialog.dismiss()
                }, 300)
            }


            //二次弹框
            confirmBinding.btnAgree.onThrottleClick {
                onAgree()
                confirmDialog.dismiss()
            }

            confirmBinding.btnDisagree.onThrottleClick {
                onDisagree()
                confirmDialog.dismiss()
            }

            binding.btnDisagree.onThrottleClick {
                privacyDialog.dismiss()
                confirmDialog.show()
            }
        }
    }

    private fun buildPrivacyContent(): CharSequence {
        return buildSpannedString {
            append(
                SpanUtils.makeSpan(
                    "欢迎您使用${context.getString(R.string.app_name)}!:",
                    ForegroundColorSpan(context.getColor(R.color.primaryText)),
                    AbsoluteSizeSpan(14, true)
                )
            ).append("\n")
            append("我们将通过")
            append(
                SpanUtils.makeSpan(
                    "《服务协议》", UrlClickableSpan(
                        AdInfoCache.buildUserAgreementUrl(),
                        context.getColor(R.color.primaryBlue),
                        "服务协议"
                    )
                )
            )
            append("和")
            append(
                SpanUtils.makeSpan(
                    "《隐私协议》", UrlClickableSpan(
                        AdInfoCache.buildPrivacyAgreementUrl(),
                        context.getColor(R.color.primaryBlue),
                        "隐私协议"
                    )
                )
            )
            append("帮助您了解我们为您提供的服务，以及收集、处理个人信息的方式。\n")
            append(SpanUtils.makeSpan("[space]", QMUIBlockSpaceSpan(context.dip(4))))
            append(
                SpanUtils.makeSpan(
                    "现向您做如下说明:",
                    ForegroundColorSpan(context.getColor(R.color.primaryText)),
                    AbsoluteSizeSpan(14, true)
                )
            ).append("\n")
            append(SpanUtils.makeSpan("[space]", QMUIBlockSpaceSpan(context.dip(4))))
            append("* 我们会申请系统收集设备信息、日志信息:其中包括: 安卓ID 、应用列表、移动设备型号、移动设备系统版本、APP版本号、互联网服务提供商、网络状态、IP地址、MAC地址、IMEI、IMSI信息、地理位置。用于统计APP的使用情况、定位错误问题和不断提供APP稳定性、安全性;\n")
            append(SpanUtils.makeSpan("[space]", QMUIBlockSpaceSpan(context.dip(4))))
            append("* 我们会尽力采取各种安全技术保护您的个人信息，未经您的同意，我们不会从第三方获取、共享或对外提供您的信息；\n")
            append(SpanUtils.makeSpan("[space]", QMUIBlockSpaceSpan(context.dip(4))))
            append("* 您可以访问、更正、删除您的个人信息，我们提供意见反馈功能入口。如您已阅读并同意政策，请点击“同意”，开始使用我们的产品和服务。\n")
            append(SpanUtils.makeSpan("[space]", QMUIBlockSpaceSpan(context.dip(4))))
            append(
                SpanUtils.makeSpan(
                    "${context.getString(R.string.app_name)}稍后会向您申请获取相关权限，在此，我们会对一些重要权限做说明，请您仔细审阅并理解:",
                    ForegroundColorSpan(context.getColor(R.color.primaryText)),
                    AbsoluteSizeSpan(14, true)
                )
            ).append("\n")
            append(SpanUtils.makeSpan("[space]", QMUIBlockSpaceSpan(context.dip(8))))
            append("* 我们会申请存储空间权限信息，申请该权限是为了获取缓存信息，实现应用软件功能；\n")
        }

    }

    private fun buildTipsContent(isStrict: Boolean = false): CharSequence {
        return buildSpannedString {
            append("查看完整版")
            append(
                SpanUtils.makeSpan(
                    "《服务协议》", UrlClickableSpan(
                        AdInfoCache.buildUserAgreementUrl(),
                        context.getColor(R.color.primaryBlue),
                        "服务协议"
                    )
                )
            )
            append("和")
            append(
                SpanUtils.makeSpan(
                    "《隐私协议》", UrlClickableSpan(
                        AdInfoCache.buildPrivacyAgreementUrl(),
                        context.getColor(R.color.primaryBlue),
                        "隐私协议"
                    )
                )
            )
        }


    }

    fun show() {
        privacyDialog.show()
    }

}